package net.xfok.widget;

import java.util.Random;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class MyWidget extends AppWidgetProvider{
	private static final String TAG="MyWidget";
	private boolean flag=false;

	private RemoteViews views;
	private Context mContext;
	
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
		Log.i(TAG, "onUpdate");
		initWidget(context);
		updateWidget(appWidgetManager, appWidgetIds);
		super.onUpdate(context, appWidgetManager, appWidgetIds);		
	}
	
	public void onReceive(Context context, Intent intent){
		initWidget(context);
		String action=intent.getAction();
		Log.i(TAG, "onReceive:======>"+action);
		if(action.startsWith("net.xfok.widget")){
			flag=true;
			updateWidget(null, null);
		}
		super.onReceive(context, intent);
	}
	
	private void initWidget(Context context){
		mContext=context;
		if(views==null){
			views=new RemoteViews(context.getPackageName(), R.layout.widget_layout);
		}
	}
	
	private void updateWidget(AppWidgetManager appWidgetManager,int[] appWidgetIds){
		Log.i(TAG, "==========>updateWidget");
//		for(int i=0;i<appWidgetIds.length;i++){
			//start a activity
			Intent intent=new Intent(mContext,MyActivity.class);
			PendingIntent pendingIntent=PendingIntent.getActivity(mContext, 0, intent, 0);
			views=new RemoteViews(mContext.getPackageName(), R.layout.widget_layout);
			views.setOnClickPendingIntent(R.id.image, pendingIntent);			
			//start a service
			intent=new Intent("net.xfok.widget.MyService");	
			pendingIntent=PendingIntent.getService(mContext, 0, intent, 0);
			if(flag)views.setTextViewText(R.id.ss, randStr());
			views.setOnClickPendingIntent(R.id.ss, pendingIntent);
			//send a broadcast
			intent=new Intent("net.xfok.widget.MyBroadcast");	
			pendingIntent=PendingIntent.getBroadcast(mContext, 0, intent, 0);
			if(flag)views.setTextViewText(R.id.sb, randStr());
			views.setOnClickPendingIntent(R.id.sb, pendingIntent);				
//		}
		flag=false;
		if (appWidgetManager == null)
			appWidgetManager = AppWidgetManager.getInstance(mContext);
		if (appWidgetIds != null)
			appWidgetManager.updateAppWidget(appWidgetIds, views);
		else
			appWidgetManager.updateAppWidget(new ComponentName(mContext, MyWidget.class), views);
	}
	
	private String randStr(){
		String[] strs={"Cake","Back","Think","Good","Beef"};
		Random ran=new Random();
		return strs[ran.nextInt(strs.length)];
	}
}